package targetToOffer.seventhDay;

/**
 * @author Godc
 * @description
 */
public class GetKthFromEnd {
}
class GetKthFromEndSolution {
    public ListNode getKthFromEnd(ListNode head, int k) {
        if(head == null) return  null;
         ListNode temp = head;
         int len = 0;
         while(temp!=null){
             len++;
             temp = temp.next;
         }
        for (int i = 0; i < len -k; i++) {
            head = head.next;
        }
        return head;
    }
    /**
     * 双指针做法不需要知道链表长度
     */
    public ListNode getKthFromEnd1(ListNode head, int k){
        if(head == null) return  null;
        ListNode t1 = head,t2=head;
        // 先让指针1走k-1步，然后两指针同步移动。指针1到尾部，指针2就到了目标位置
        for (int i = 0; i < k-1; i++) {
            t1 = t1.next;
        }
        while(t1.next!=null){
            t1 = t1.next;
            t2 = t2.next;
        }
        return t2;
    }
}